package dev;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.Collecte;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Query.SortDirection;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

public class Clean_NantesServlet extends HttpServlet {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private ArrayList<Collecte> tab_collecte  ;
    @SuppressWarnings("deprecation")
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
              throws IOException {
        UserService userService = UserServiceFactory.getUserService();
        User user = userService.getCurrentUser();
        String recherche = null ;
        if(req.getParameter("recherche") != null){
        	recherche = (String)req.getParameter("recherche") ;
        }
        
        if (user != null) {
        	DatastoreService datastore = DatastoreServiceFactory
    				.getDatastoreService();
        	Query q = new Query("Collecte");
    		q.addFilter("user_email", Query.FilterOperator.EQUAL, user.getEmail());
    		q.addSort("date", SortDirection.DESCENDING);
    		PreparedQuery pq = datastore.prepare(q);

    		ArrayList<Entity> addr_saved = new ArrayList<Entity>();
    		for (Entity result : pq.asIterable()) {
    			addr_saved.add(result);
    		}
    		if(addr_saved.size()>0){
    			req.setAttribute("addrSaved", addr_saved.get(0).getProperty("adresse"));
    		}
        	
        	if(recherche!=null){
        		tab_collecte = new ArrayList<Collecte>() ;
	        	ArrayList<String> lignes = new ArrayList<String>();
	        	URL url = new URL("http://data.nantes.fr/api/publication/JOURS_COLLECTE_DECHETS_VDN/JOURS_COLLECTE_DECHETS_VDN_STBL/content/?format=csv");
	        	//String url = "/Users/xaviergougat/Documents/workspace/Clean-Nantes/war/contenu.csv";
	        	lignes = lireFichier(url);
	        	for(int i = 0; i<lignes.size();i++){
	        		String[] elts = lignes.get(i).split(",");
	        		Collecte collecte = new Collecte(elts[0],elts[1],elts[2],elts[3],elts[4],elts[5],elts[6],elts[7],elts[8],elts[9],elts[10],elts[11],elts[12],elts[13],elts[14]) ;
	            	tab_collecte.add(collecte);
	        	}
	        	
	        	ArrayList<Integer> trouves = new ArrayList<Integer>() ;
	        	for(int i = 0;i<tab_collecte.size();i++){
	        		if(tab_collecte.get(i).search(recherche)){
	        			trouves.add(i) ;
	        		}
	        	}
	        	ArrayList<Collecte> infos = new ArrayList<Collecte>();
	        	for(int i = 0 ; i<trouves.size();i++){
	        			infos.add(tab_collecte.get(trouves.get(i)));
	        	}
	        	
	        	
	     
	        	req.setAttribute("infos", infos);
	        	req.setCharacterEncoding("UTF-8");
	        	resp.setContentType("text/html; charset=UTF-8");

	            
	        	try {
					getServletContext().getRequestDispatcher("/index.jsp").forward(req, resp);
				} catch (ServletException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
        	}else{
        		try {
					getServletContext().getRequestDispatcher("/index.jsp").forward(req, resp);
				} catch (ServletException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
        	}
        } else {
            resp.sendRedirect(userService.createLoginURL(req.getRequestURI()));
        }
    }
    
    public ArrayList<String> lireFichier(URL url) {

		BufferedReader br = null;
		ArrayList<String> lignes = new ArrayList<String>();
		try {
			String sCurrentLine;

			br = new BufferedReader(new InputStreamReader(url.openStream()));

			while ((sCurrentLine = br.readLine()) != null) {
				lignes.add(sCurrentLine);
			}

		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (br != null)
					br.close();
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
		return lignes;

	}
    
    public ArrayList<String> lireFichierLocal(String fichier) throws IOException
    {
    	ArrayList<String> lignes = new ArrayList<String>();
      BufferedReader lecteurAvecBuffer = null;
      String ligne;

      try
        {
    	  lecteurAvecBuffer = new BufferedReader(new FileReader(fichier));
        }
      catch(FileNotFoundException exc)
        {
  	System.out.println("Erreur d'ouverture");
        }
      while ((ligne = lecteurAvecBuffer.readLine()) != null)
        lignes.add(ligne);
      lecteurAvecBuffer.close();
      return lignes ;
    }

	public ArrayList<Collecte> getTab_collecte() {
		return tab_collecte;
	}

	public void setTab_collecte(ArrayList<Collecte> tab_collecte) {
		this.tab_collecte = tab_collecte;
	}
}